<?php
/*
RPHP Core
 */

class RPHP
{

    protected static $_instance = null;
    /*
    global config paras
     */
    public $_config;
    public $_dbconfig;
    /*
    loaded class
     */

    public function __construct()
    {

        /*---加载框架------*/
        $list = array(
            //核心
            "Model.php", //模型
            "View.php", //视图
            "Controller.php", //控制
            "Router.php", //路由
            //库
            LIB_PATH . "/Rfc.php", //RFC
        );
        foreach ($list as $key => $file) {
            include $file;
        }

    }

    public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    /*
     * Load Class
     */
    public function loadClass($class, $dir)
    {

        if (is_string($class) && $class != "") {

            //$class = str_replace(array('.', '#'), array('/', '.'), $class);

            $classfile = $dir . DIRECTORY_SEPARATOR . $class . ".php";
            //echo $classfile."<br>";
            if (file_exists($classfile)) {
                include $classfile;
                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }

    }

    /*
     * Load Config
     */
    public function loadConfig($conf, $ext = '.php')
    {
        if (is_string($conf) && $conf != "") {

            $conf = str_replace(array('.', '#'), array('/', '.'), $conf);

            $conffile = $conf . $ext;
            if (file_exists($conffile)) {
                return include $conffile;
            } else {
                return false;
            }

        } else {
            return false;
        }

    }

    public function dispatch()
    {
        $router = RPHP_Router::getInstance()->dynamicMatch();
        if (is_array($router)) {

            $model      = $router['model'];
            $controller = $router['controller'];
            $action     = $router['action'];

            if (isset($controller) && isset($model)) {
                if (self::loadClass($model, $this->_config['_homes']['_controllerhome'])) {
                    try {
                        $cls = new $controller($this->_config, $router);
                    } catch (Exception $e) {}
                }

            }
            $show404 = false;
            if (!$cls) {
                $show404 = true;
            } elseif (isset($action) && $cls) {
                $func = isset($cls) ? array($cls, $action) : $action;
                if (method_exists($controller, $action)) {
                    call_user_func($func);
                } else {
                    $show404 = true;
                }

            }

            if ($show404) {
                RPHP_View::getInstance()->display(404);
            }

        }

    }
}
